using EFCoreEnterpriseDemo.Data;
using EFCoreEnterpriseDemo.Extensions;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml;
using OfficeOpenXml.Table;
using System.Linq.Expressions;

public interface IDataImportExportService
{
    Task<byte[]> ExportToExcelAsync<T>(
        Expression<Func<T, bool>> predicate,
        List<string>? includeFields = null) where T : class;

    Task<ImportResult<T>> ImportFromExcelAsync<T>(
        Stream excelStream,
        Func<T, Task<ValidationResult>>? validator = null) where T : class;
}

public class ImportResult<T>
{
    public List<T> SuccessItems { get; set; } = new();
    public List<ImportError<T>> Errors { get; set; } = new();
    public int TotalCount { get; set; }
}

public class ImportError<T>
{
    public T? Item { get; set; }
    public int RowNumber { get; set; }
    public string? ErrorMessage { get; set; }
    public Dictionary<string, string>? FieldErrors { get; set; }
}

public class DataImportExportService : IDataImportExportService
{
    private ApplicationDbContext _context;

    public DataImportExportService(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<byte[]> ExportToExcelAsync<T>(
        Expression<Func<T, bool>> predicate,
        List<string>? includeFields = null) where T : class
    {
        throw new NotImplementedException();
        //var query = _context.Set<T>().Where(predicate);

        //// 应用字段权限
        //if (includeFields != null)
        //{
        //    query = query.SelectFields(includeFields);
        //}

        //var data = await query.ToListAsync();

        //using var package = new ExcelPackage();
        //var worksheet = package.Workbook.Worksheets.Add(typeof(T).Name);

        //// 自动映射实体到Excel
        //worksheet.Cells["A1"].LoadFromCollection(data, true, TableStyles.None);

        //// 格式化
        //var range = worksheet.Dimension.Address;
        //worksheet.Cells[range].AutoFitColumns();

        //return package.GetAsByteArray();
    }

    public async Task<ImportResult<T>> ImportFromExcelAsync<T>(
        Stream excelStream,
        Func<T, Task<ValidationResult>>? validator = null) where T : class
    {
        throw new NotImplementedException();
        //var result = new ImportResult<T>();

        //using var package = new ExcelPackage(excelStream);
        //var worksheet = package.Workbook.Worksheets[0];

        //// 读取数据
        //var data = worksheet.ConvertSheetToObjects<T>().ToList();
        //result.TotalCount = data.Count;

        //// 验证和导入
        //foreach (var (item, index) in data.Select((item, index) => (item, index)))
        //{
        //    try
        //    {
        //        // 自定义验证
        //        if (validator != null)
        //        {
        //            var validation = await validator(item);
        //            if (!validation.IsValid)
        //            {
        //                result.Errors.Add(new ImportError<T>
        //                {
        //                    Item = item,
        //                    RowNumber = index + 2,
        //                    ErrorMessage = validation.ErrorMessage,
        //                    FieldErrors = validation.FieldErrors
        //                });
        //                continue;
        //            }
        //        }

        //        result.SuccessItems.Add(item);
        //    }
        //    catch (Exception ex)
        //    {
        //        result.Errors.Add(new ImportError<T>
        //        {
        //            Item = item,
        //            RowNumber = index + 2,
        //            ErrorMessage = ex.Message
        //        });
        //    }
        //}

        //// 批量插入
        //if (result.SuccessItems.Any())
        //{
        //    await _context.BulkInsertAsync(result.SuccessItems);
        //}

        //return result;
    }
}